var express = require('express');
var router = express.Router();
var User = require('../models/User');
/**
 *  用户注册
 *    注册逻辑
 * 
 *    1.用户名不能为空
 *    2.密码不能为空
 *    3.两次输入密码必须一致
 *    4.用户是否已经注册 
 */

//  统一返回格式
  var responseData = {
    code:0,
    message:''
  }

// //  默认
//  router.use((req,res,next) => {
//   responseData = {
//     code:0,
//     message:''
//   }
//  });

//  post请求
router.post('/user/register', (req, res, next) => {
  console.log(req.body);
  var username = req.body.username;
  var password = req.body.password;
  var rePassword = req.body.rePassword;

  // 用户是否为空
  if(username == '') {
    responseData.code = '1';
    responseData.message = '用户名不能为空';
    res.json(responseData);
    return;
  }
  // 密码不能为空
  if(password == '') {
    responseData.code = '2';
    responseData.message = '密码不能为空';
    res.json(responseData);
    return;
  }

  // 两次输入的密码必须一致
  if(password != rePassword) {
    responseData.code = '3';
    responseData.message = '两次输入的密码不一致';
    res.json(responseData);
    return;
  }

  // 判断用户名是否已经被注册
  User.findOne({
    username:username
  }).then((userInfo) => {
    if(userInfo) {
      responseData.code = 4;
      responseData.message = '用户名已经被注册';
      res.json(responseData);
      return;
    }
    // 保存用户注册的信息到数据库
    var user = new User({
      username: username,
      password:password,
    });
    return user.save();
  }).then((newUserInfo) => {
    responseData.message = '注册成功';
    res.json(responseData);
  })
});

module.exports = router;